package org.dftproject.genesis.core.persistence;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dftproject.genesis.core.Activator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;

public class PersistenceUtils {

	private static final Log log = LogFactory.getLog(PersistenceUtils.class);

	public static IPersistenceFactory getFactory(String id) {
		if (id == null)
			return null;

		IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(Activator.ID, Activator.PERSISTENCE_FACTORIES_EXTENSION_POINT);
		for (IExtension extension : extensionPoint.getExtensions()) {
			for (IConfigurationElement configElement : extension.getConfigurationElements()) {
				if (id.equals(configElement.getAttribute("id"))) {
					try {
						Object factory = configElement.createExecutableExtension("class");
						if (factory instanceof IPersistenceFactory)
							return (IPersistenceFactory) factory;
					} catch (CoreException e) {
						log.error("Failed to create persistence factory '" + id + "'", e);
					}
				}
			}
		}

		return null;
	}

}
